package com.bdqn.zhao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.zhao.config.Convert;
import com.bdqn.zhao.dao.RoleDeptMapper;
import com.bdqn.zhao.dao.SysRoleMapper;
import com.bdqn.zhao.dao.SysRoleMenuMapper;
import com.bdqn.zhao.pojo.RoleDept;
import com.bdqn.zhao.pojo.SysRole;
import com.bdqn.zhao.service.SysRoleService;
import com.bdqn.zhao.xing.exception.BusinessException;
import com.bdqn.zhao.xing.pojo.SysRoleMenu;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author zhangsan
 * @since 2023-04-24
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private RoleDeptMapper roleDeptMapper;

    @Override
    public Page<SysRole> listt(Integer pageNum, Integer pageSize, String sortField, String sortOrder, Integer status, String roleName) throws Exception {
        LambdaQueryWrapper<SysRole> sysRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (sortField != null && sortField.equals("createTime")) {
            if (sortOrder != null && sortOrder.equals("desc")) {
                sysRoleLambdaQueryWrapper.orderByDesc(SysRole::getCreateTime);
            }
        }
        if (status == null) {
            sysRoleLambdaQueryWrapper.eq(StringUtils.isNotBlank(roleName), SysRole::getRoleName, roleName);
        }
        if (status != null && status == 1 || status != null && status == 0) {
            sysRoleLambdaQueryWrapper.eq(StringUtils.isNotBlank(roleName), SysRole::getRoleName, roleName).eq(true, SysRole::getStatus, status);
        }

        Page<SysRole> page = new Page<>(pageNum, pageSize);
        return sysRoleMapper.selectPage(page, sysRoleLambdaQueryWrapper);
    }

    @Override
    public Integer updateStatus(Integer id, Integer status) {
        SysRole sysRole = new SysRole();
        sysRole.setStatus(String.valueOf(status));
        sysRole.setRoleId(id);
        return sysRoleMapper.updateById(sysRole);
    }

    @Override
    public Integer delByIds(List<Integer> ids) throws Exception {
        if (ids == null || ids.size() == 0) {
            return 0;
        }
        if (ids.size() == 1) {
            sysRoleMapper.deleteById(ids.get(0));
        } else {
            for (Integer id : ids) {
                int i = sysRoleMapper.deleteById(id);
                if (i == 0) {
                    throw new Exception();
                }
            }
        }
        return 1;
    }

    @Override
    public boolean deleteRoleById(Long roleId) {
        return false;
    }

    /**
     * 批量删除角色信息
     *
     * @param ids 需要删除的数据ID
     * @throws Exception
     */
    @Override
    public int deleteRoleByIds(String ids) throws Exception {
        Long[] roleIds = Convert.toLongArray(ids);
        for (Long roleId : roleIds) {
            SysRole role = selectRoleById(roleId);
            //通过角色ID查询角色使用数量 如果大于0 则 不可以删除
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }

        }
        if (roleIds.length > 0) {
            return sysRoleMapper.deleteRoleByIds(roleIds);
        }
        return 0;
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
        return sysRoleMapper.countUserRoleByRoleId(roleId);
    }


    @Override
    public SysRole selectRoleById(Long roleId) {
        return sysRoleMapper.selectById(roleId);
    }

    @Override
    public int insertRole(SysRole role) {
        if (BooleanUtils.isTrue(role.getIsDefault())) {
            sysRoleMapper.clearDefault();
        }
        sysRoleMapper.insertRole(role);
        return insertRoleMenu(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRole(SysRole role) {
        //如果新增的是true 那么修改之前的默认角色为flase
        if (BooleanUtils.isTrue(role.getIsDefault())) {
            sysRoleMapper.clearDefault();
        }
        // 修改角色信息
        sysRoleMapper.updateRole(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId().longValue());
        return insertRoleMenu(role);
    }


    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        if (role.getMenuIds() != null || role.getMenuIds().size() > 0) {
            for (Long menuId : role.getMenuIds()) {
                SysRoleMenu rm = new SysRoleMenu();
                rm.setRoleId(role.getRoleId());
                rm.setMenuId(Math.toIntExact(menuId));
                list.add(rm);
            }
            if (list.size() > 0) {
                rows = roleMenuMapper.batchRoleMenu(list);
            }
        }
        return rows;
    }


    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(SysRole role) {
        // 修改角色信息
        sysRoleMapper.updateRole(role);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId().longValue());
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role);
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(SysRole role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<RoleDept> list = new ArrayList<RoleDept>();
        if (role.getDeptIds() != null || role.getDeptIds().length > 0) {
            for (Long deptId : role.getDeptIds()) {
                RoleDept rd = new RoleDept();
                rd.setRoleId(role.getRoleId().longValue());
                rd.setDeptId(deptId);
                list.add(rd);
            }
            if (list.size() > 0) {
                rows = roleDeptMapper.batchRoleDept(list);
            }
        }
        return rows;
    }

    @Override
    public List<SysRole> selectRoleAll(SysRole role) {
        return sysRoleMapper.selectRoleList(role);
    }
}
